package com.bretagne5.radio.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.bdd.chronokayak.JSONParser;

public class JsonEmissionParser {
	
	private JsonParse listener ;
	private JSONObject jsonObject ;
	private JSONParser jsonParser ;
	private String day ;
	private ArrayList<Emission> emissionsMap ;
	
	
	public JsonEmissionParser(final JsonParse listener , final String day){
		
		this.day = day ;
		this.listener = listener ;
		
		jsonObject = new JSONObject();
		jsonParser = new JSONParser();
		emissionsMap = new ArrayList<Emission>();
		
	}
	
	public void getDatas(){
		
		new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... param) {

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("day",day));
				
				jsonObject = jsonParser.makeHttpRequest("http://www.bretagne5.fr/android/programme.php", "POST", params);
				
				Log.d("jsonResult", jsonObject.toString());
				
				
				return null;
			}
			
			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				
				JSONArray jsonArray ;
				
				try {
					
					if (jsonObject.getInt("result") != 1 )
						listener.onFinish(null);
					
					jsonArray = jsonObject.getJSONArray("emission");
					
					for (int i = 0 ; i < jsonArray.length() ; i++){
						JSONObject tempJson = jsonArray.getJSONObject(i);
					
						Emission emission = new Emission();
						emission.setTitle(tempJson.getString("title"));
						emission.setContent(tempJson.getString("content"));
						emission.setStartTime(tempJson.getString("time_start"));
						emission.setEndTime(tempJson.getString("time_end"));
						emission.setUrlImage(tempJson.getString("url_img"));
						
						emissionsMap.add(emission);
						
					}
					
					listener.onFinish(emissionsMap);

				} catch (JSONException e) {
					listener.onFinish(null);
					e.printStackTrace();
				}
				
				
			}
		}.execute();
	
	}
	

	public interface JsonParse {
		
		void onFinish(ArrayList<Emission> result);
	}

}
